package com.xb.chain.entity;

import com.xb.chain.transaction.Transaction;
import lombok.Data;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author xiaobin
 * @date 2020/2/19 16:17
 * @desc 区块实体类
 */
@Data
public class Block {
    private String previousHash;        // 上一个区块Hash
    private String blockHash;           // 区块hash
    private long time;                  // 时间time
    private Integer nonce;              // 工作量证明
    private List<Transaction> transactions; //交易信息

    public Block(String previousHash, List<Transaction> transactions) {
        this.previousHash = previousHash;
        this.time = new Date().getTime();
        this.transactions = transactions;
    }


    /**
     * 转账操作
     *
     * @return
     */
    public void transfer(String from, String to, BigDecimal value) {
        this.transactions.add(new Transaction(from, to, value));
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("Block{");
        sb.append("previousHash='").append(previousHash).append('\'');
        sb.append(", blockHash='").append(blockHash).append('\'');
        sb.append(", time=").append(time);
        sb.append(", nonce=").append(nonce);
        sb.append(", transactions=").append(transactions);
        sb.append('}');
        return sb.toString();
    }
}
